import React, { useEffect, useState } from 'react';
import './Favorites.css';
import { Link } from 'react-router-dom';  
import { getHot } from '../api/userApi'; // 确保路径正确
import { useNavigate } from 'react-router-dom'; 

const Hotpost = () => {
  const [hottopics, setHottopics] = useState([]); // 状态管理
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [userId, setUserId] = useState(null);
  const navigate = useNavigate();
  // 页面跳转函数
  const handleNavigate = (path) => {
    navigate(path);  // 通过 navigate 进行跳转
  };

  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
    }
  }, []);

  
  useEffect(() => {
    const fetchHotTopics = async () => {
      if (!userId) {
        console.error('User ID is missing');
        return;
      }
      try {
        const topics = await getHot(userId);
        setHottopics(topics);
        console.log('fetchHotTopics:', topics);
        setError(null); // 清除错误状态
      } catch (error) {
        setError(error.message);
      } finally {
        setLoading(false);
      }
    };
  
    fetchHotTopics();
  }, [userId]);
  


  if (loading) return <p>加载中...</p>;

  if (error) return <p>错误: {error}</p>;

  // 渲染话题数据
  const topics = hottopics.map((topic) => ({
    interestId: topic.interestId, 
    title: topic.name,
  }));

  return (
    <div className="favorites">
      <div className='favorites-header'>
        <h2>热门话题</h2>      
      </div>
      <div className="favorites-list">
        {topics.length > 0 ? (
          topics.map((topic) => (
            <div key={topic.interestId} className="favorite-item">
              <p onClick={() => handleNavigate(`/topic/${topic.interestId}`)}>#{topic.title}</p>
            </div>
          ))
        ) : (
          <p>目前没有热门的帖子。</p>
        )}
      </div>
    </div>
  );
};

export default Hotpost;
